import Taro from "@tarojs/taro";

let requsetUrls = []

export function requestData(url, data, method = 'POST', access_token, user_id) {
  return new Promise((resolve, reject) => {
    Taro.request({
      url: url.indexOf('https') === -1 ? 'https://ya30api.hbwlife.com/wxmp' + url : url,
      method: method,
      header: {
        "AUTH-TOKEN": user_id + "|" + access_token
      },
      data: data,
      success: (res) => {
        if (typeof res?.data == 'object' && !Array.isArray(res?.data) && res?.data?.code ==
          0 || Array.isArray(res?.data)) {
          resolve(res)
        } else if (res?.data?.code == -57004) {
          //reject("无权操作")
          // Taro.showToast({
          // 	title: '请先绑定手机号',
          // 	icon: 'none',
          // });
          // setTimeout(() => {
          // 	Taro.navigateTo({
          // 		url: '/pages/loginPhone/loginPhone',
          // 	})
          // }, 1000)
        } else if (res?.data?.code == -56055) {
          reject("Token失效")
        } else {
          reject(res?.data || {})
        }
      },
      fail: () => {}
    })
  })
}

function refershRequest(isLogin = false, data) {
  return new Promise((resolve, reject) => {
    if (requsetUrls.length) {
      let {
        url,
        data,
        method,
      } = requsetUrls[0]
      if (!isLogin) {
        Taro.login({
          success: (res) => {
            requsetUrls.shift()
            //console.log(res.code)
            Taro.request({
              url: 'https://ya30api.hbwlife.com/wxmp/wxaccess/mp/user/login',
              method: 'POST',
              header: {},
              data: {
                "wxlogin_code": res.code
              },
              success: (res) => {
                Taro.removeStorageSync('user_id');
                Taro.removeStorageSync('access_token');
                Taro.removeStorageSync('user_id');
                Taro.setStorageSync('user_id', res.data.datas
                  .user_id);
                Taro.setStorageSync('user_id', res.data.datas
                  .user_id);
                Taro.setStorageSync('access_token', res.data
                  .datas.access_token);
                Taro.setStorageSync('mobile_binded', res.data
                  .datas.mobile_binded);
                requestData(
                  url,
                  data,
                  method,
                  res.data.datas.access_token,
                  res.data.datas.user_id
                ).then(res => {
                  resolve(res)
                }).catch(err => {
                  reject(err)
                })
              },
              fail: () => {

              }
            })
          },
          fail: (err) => {
            console.log(err)
          }
        })
      } else {
        let user_id = Taro.getStorageSync('user_id');
        let access_token = Taro.getStorageSync('access_token');
        requestData(
          url,
          data,
          'POST',
          access_token,
          user_id
        ).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      }
    } else {
      resolve(data)
    }
  })
}

export function request(url, data, method = 'POST') {
  return new Promise((resolve, reject) => {
    let user_id = Taro.getStorageSync('user_id');
    let access_token = Taro.getStorageSync('access_token');
    Taro.request({
      url: 'https://ya30api.hbwlife.com/wxmp' + url,
      method: method,
      header: {
        "AUTH-TOKEN": user_id + "|" + access_token
      },
      data: data,
      success: (res) => {
        if(url.indexOf('/mp/user/getPhoneNumber') !== -1) {
          resolve(res.data)
        }
        else {
          if (res?.data?.code == 0) {
            refershRequest(true, res?.data).then(res => {
              resolve(res || {})
            }).catch(err => {
              reject(err || '')
            })
          }
          else if(res?.data?.code == -56055){
            // reject("Token失效")
            let index = requsetUrls.findIndex(item => item.url == url)
            if (index == -1) {
              requsetUrls.push({
                url,
                data,
                method
              })
            }
            refershRequest().then(res => {
              console.log(res)
              resolve(res?.data || {})
            }).catch(err => {
              reject(err?.msg || '')
            })
          }
          else {
            reject(res?.data?.msg)
          }
        }
      },
      fail: (err) => {
        reject(JSON.stringify(err))
      }
    })
  })
}
